﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace TravellerLib {
  /// <summary>
  /// A static class for utility fuctions.
  /// </summary>
  public static class TravellerUtils {
    /// <summary>
    /// Converts a Traveller hex string to a pair of Cartesian coordinates stored in a <see cref="Tuple"/>.
    /// </summary>
    /// <param name="c">The hex string.</param>
    /// <returns>The coordinates</returns>
    /// <exception cref="System.ArgumentException">Cordinate must be in the format XXYY.</exception>
    public static Tuple<int, int> TravellerToCartesian(string c) {
      if (c.Length != 4)
        throw new ArgumentException("Cordinate must be in the format XXYY.");
      if (!Regex.IsMatch(c, @"\d{4}"))
        throw new ArgumentException("Cordinate must be in the format XXYY.");
      int n = Convert.ToInt32(c);
      return Tuple.Create(n / 100, n % 100);
    }
    /// <summary>
    /// Converts a Cartesian hex coordinate (x,y) to a Traveller hex number.
    /// </summary>
    /// <param name="x">The x coordinate.</param>
    /// <param name="y">The y coordinate.</param>
    /// <returns>The Traveller hex number.</returns>
    /// <exception cref="System.ArgumentOutOfRangeException">X coordinate must be in the range 1-32.</exception>
    public static string CartesianToTraveller(int x, int y) {
      if (x < 1)
        throw new ArgumentOutOfRangeException("X coordinate must be in the range 1-32.");
      if (y < 1)
        throw new ArgumentOutOfRangeException("Y coordinate must be in the range 1-40.");
      return x.ToString("00") + y.ToString("00");
    }
    /// <summary>
    /// Converts a Cartesian coordinate stored in a <see cref="Tuple"/> into a Traveller hex number.  Reverses <see cref="TravellerToCartesian"/>.
    /// </summary>
    /// <param name="coordinate">The coordinate.</param>
    /// <returns>The Traveller hex number.</returns>
    /// <seealso cref="TravellerToCartesian"/>
    public static string CartesianToTraveller(Tuple<int, int> coordinate) {
      return CartesianToTraveller(coordinate.Item1, coordinate.Item2);
    }
  }
}
